#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->label->resize(AGNES_SCREEN_WIDTH, AGNES_SCREEN_HEIGHT);
    emu = new Emulator(this);
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::display);
    player1 = {false, false, false, false, false, false, false, false};
    player2 = player1;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mouseDoubleClickEvent(QMouseEvent *event)
{
    if (timer->isActive())
    {
        timer->stop();
    }
    QString romfile = QFileDialog::getOpenFileName(this);
    if (emu->load(romfile))
    {
        timer->start(1000/60);
    }
}

void Widget::display()
{
    QImage frame(AGNES_SCREEN_WIDTH, AGNES_SCREEN_HEIGHT, QImage::Format_RGB888);
    emu->step(frame, &player1, nullptr);
    frame = frame.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->label->setPixmap(QPixmap::fromImage(frame));
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Up)
    {
        player1.up = true;
    }

    if (event->key() == Qt::Key_Down)
    {
        player1.down = true;
    }

    if (event->key() == Qt::Key_Left)
    {
        player1.left = true;
    }

    if (event->key() == Qt::Key_Right)
    {
        player1.right = true;
    }

    if (event->key() == Qt::Key_Space)
    {
        player1.select = true;
    }

    if (event->key() == Qt::Key_Return)
    {
        player1.start = true;
    }

    if (event->key() == Qt::Key_Z)
    {
        player1.a = true;
    }

    if (event->key() == Qt::Key_X)
    {
        player1.b = true;
    }
}

void Widget::keyReleaseEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Up)
    {
        player1.up = false;
    }

    if (event->key() == Qt::Key_Up)
    {
        player1.down = false;
    }

    if (event->key() == Qt::Key_Left)
    {
        player1.left = false;
    }

    if (event->key() == Qt::Key_Right)
    {
        player1.right = false;
    }

    if (event->key() == Qt::Key_Space)
    {
        player1.select = false;
    }

    if (event->key() == Qt::Key_Return)
    {
        player1.start = false;
    }

    if (event->key() == Qt::Key_Z)
    {
        player1.a = false;
    }

    if (event->key() == Qt::Key_X)
    {
        player1.b = false;
    }
}
